﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;

namespace DIfmClient
{
    public static class ListManager
    {
        public static List<Channel> RetrieveChannels(string jsonUrl)
        {
            string jsonString = String.Empty;

            using (WebClient client = new WebClient())
            {
                jsonString = client.DownloadString(jsonUrl);
            }

            List<Channel> channels = new List<Channel>();
            channels = JsonConvert.DeserializeObject<List<Channel>>(jsonString);
            var tempChannels = (from c in channels orderby c.Name select c);
            channels = new List<Channel>();

            foreach (Channel c in tempChannels)
            {
                channels.Add(c);
            }

            return channels;
        }

        public static List<Track> RetrievePlaylist(string trackHistory, Channel c)
        {
            List<Track> trackList = new List<Track>();
            string jsonString = String.Empty;
            string trackHistoryUrl = trackHistory + c.ID + ".json";
            
            using (WebClient client = new WebClient())
            {
                jsonString = client.DownloadString(trackHistoryUrl);
            }

            trackList = JsonConvert.DeserializeObject<List<Track>>(jsonString);
            
            //remove ads from tracklist
            trackList.RemoveAll(t => t.length == null);

            return trackList;
        }
    }
}
